package com.ruoyi.web.controller.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.ruoyi.common.config.CosConfig;
import com.ruoyi.common.config.lphCosConfig;
import com.ruoyi.system.domain.Book;
import com.ruoyi.system.domain.ZhyCollect;
import com.ruoyi.system.service.BookService;
import com.ruoyi.system.service.ZhyCollectService;
import com.ruoyi.web.controller.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class BookController {
    @Autowired
    private ZhyCollectService ZhycollectServices;
    @Autowired
    private BookService bookService;
    @RequestMapping("/book/{pageNum}")
    public R<List<Book>> selectAll(@PathVariable("pageNum") Integer pageNum)
    {
        PageHelper.startPage(pageNum,6);
        List<Book> select =bookService.select();
        PageInfo<Book> pageInfo= new PageInfo<>(select);
        return R.success(select.size(),select);
    }
    @PostMapping("/book/selectName/{pageNum}")
    public R<List<Book>> selectName(@PathVariable("pageNum") Integer pageNum,@RequestBody Book book)
    {
        PageHelper.startPage(pageNum,6);
        List<Book> selectname = bookService.selectname(book.getName());
        PageInfo<Book> pageInfo= new PageInfo<>(selectname);
         return  R.success(selectname.size(),selectname);
    }
    @RequestMapping("/book/update")
    public R<String> updateStatus(@RequestParam("id") int id,@RequestParam("introduce") String introduce, @RequestParam("classify") int classify, @RequestParam("classifyname") int classifyname, @RequestParam("name") String name, @RequestParam("status") int status,@RequestParam(value="photoFile",required=false) MultipartFile photoFile)
    {
        Book book = bookService.selectBookByid(id);
        book.setStatus(status);
        book.setClassify(classify);
        book.setClassifyname(classifyname);
        book.setIntroduce(introduce);
        book.setName(name);
        if(photoFile==null){
            bookService.updateStatus(book);
            return R.success(1, "修改成功");
        }else{
        String originalFilename = photoFile.getOriginalFilename();
        if(!originalFilename.isEmpty()) {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newfilename = UUID.randomUUID().toString() + suffix;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            COSClient cosClient = new lphCosConfig().cosClient();
            String key1 = (book.getPhoto()).substring((book.getPhoto()).lastIndexOf("/"));
            try {
                cosClient.deleteObject(new lphCosConfig().getbucket(), key1);
                String url = null;
                InputStream inputStream = photoFile.getInputStream();
                objectMetadata.setContentLength(inputStream.available());
                PutObjectRequest putObjectRequest1 = new PutObjectRequest(new lphCosConfig().getbucket(), newfilename, inputStream, objectMetadata);
                cosClient.putObject(putObjectRequest1);
                url ="https://" + new lphCosConfig().getbucket() + ".cos.ap-guangzhou.myqcloud.com" + "/" + newfilename;
                book.setPhoto(url);
                bookService.updateStatus(book);
                return R.success(1, "修改成功");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                cosClient.shutdown();
            }
        }else{
            bookService.updateStatus(book);
            return R.success(1, "修改成功");
        }
        }
        return  R.error("状态更改失败");
    }
    @PostMapping("/book/add")
    public R<String> add(@RequestParam("userid") int userid,@RequestParam("introduce") String introduce, @RequestParam("username") String username, @RequestParam("photo") MultipartFile photo, @RequestParam("book") MultipartFile book , @RequestParam("classify") int classify, @RequestParam("classifyname") int classifyname, @RequestParam("name") String name, @RequestParam("status") int status)
    {   String originalFilename = book.getOriginalFilename();
        String originalFilename1 = photo.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String suffix1 = originalFilename1.substring(originalFilename1.lastIndexOf("."));
        if( suffix.equals(".pdf")|| suffix.equals(".txt")  ){
            COSClient cosClient = new lphCosConfig().cosClient();
            String url=null;
            String url1=null;
            String newfilename= UUID.randomUUID().toString()+suffix;
            String newfilename1=new Date().getTime()+suffix1;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            ObjectMetadata objectMetadata1=new ObjectMetadata();
            try {
                InputStream inputStream = book.getInputStream();
                InputStream inputStream1 = photo.getInputStream();
                objectMetadata.setContentLength(inputStream.available());
                objectMetadata1.setContentLength(inputStream1.available());
                PutObjectRequest putObjectRequest1 = new PutObjectRequest(new lphCosConfig().getbucket(),newfilename, inputStream, objectMetadata);
                cosClient.putObject(putObjectRequest1);
                PutObjectRequest putObjectRequest2= new PutObjectRequest(new lphCosConfig().getbucket(),newfilename1,inputStream1,objectMetadata1);
                cosClient.putObject(putObjectRequest2);
                url="https://" + new lphCosConfig().getbucket() + ".cos.ap-guangzhou.myqcloud.com" + "/" + newfilename;
                url1="https://" + new lphCosConfig().getbucket() + ".cos.ap-guangzhou.myqcloud.com" + "/" + newfilename1;
                Book book1 = new Book();
                book1.setUserid(userid);
                book1.setIntroduce(introduce);
                book1.setUsername(username);
                book1.setStatus(status);
                book1.setClassify(classify);
                book1.setClassifyname(classifyname);
                book1.setPhoto(url1);
                book1.setBook(url);
                book1.setName(name);
                bookService.addBook(book1);
                return R.success(1,"添加成功");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                cosClient.shutdown();
            }
        }
        else{
            return R.error("上传格式错误");
        }
        return R.success(1,"上传成功");
    }
    @RequestMapping("/book/selectUserid/{pageNum}")
     public R<List<Book>> selectUserid(@PathVariable("pageNum") Integer pageNum,@RequestBody Book book)
    { PageHelper.startPage(pageNum,6);
        List<Book> books = bookService.selectUserid(book.getUserid());
        PageInfo<Book> pageInfo=new PageInfo<>(books);
        return  R.success(books.size(),books);
    }
    @RequestMapping("/book/selectUserid")
    public R<List<Book>> selectUserids(@RequestBody Book book)
    {
        List<Book> books = bookService.selectUserid(book.getUserid());
        return  R.success(books.size(),books);
    }
    @RequestMapping("/book/selectByid")
    public R<Book> selectByUserid(@RequestBody Book book)
    {
        Book book1 = bookService.selectBookByid(book.getId());
        book1.setLook(book1.getLook()+1);
        bookService.look(book1);
      return  R.success(1,book1);
    }
    @RequestMapping("/book/selectByclassify")
    public  R<List<Book>> selectByclassify(@RequestBody Book book)
    {
        List<Book> books = bookService.selectBookByclassify(book.getUserid(),book.getClassify(),book.getClassifyname());
         return R.success(books.size(), books);
    }
    @RequestMapping("/book/delete")
    public R<String> deleteid(@RequestBody Book book)
    {
        Book books = bookService.selectBookByid(book.getId());
        if(books==null)
            return R.error("删除失败");
        else{
            COSClient cosClient = new lphCosConfig().cosClient();
            String key=(books.getBook()).substring((books.getBook()).lastIndexOf("/"));
            String key1=(books.getPhoto()).substring((books.getPhoto()).lastIndexOf("/"));
            try {
                cosClient.deleteObject(new lphCosConfig().getbucket(),key);
                cosClient.deleteObject(new lphCosConfig().getbucket(),key1);
                bookService.delete(book.getId());
                ZhyCollect zhyCollect = new ZhyCollect();
                zhyCollect.setType("书籍");
                zhyCollect.setId(book.getId());
                ZhycollectServices.deleteCollectById(zhyCollect);
                return R.success(1,"删除文件成功");
            } catch (CosClientException e) {
                return R.error("删除文件失败");
            } finally {
                cosClient.shutdown();
            }
        }
    }
}
